<template>
  <el-container class="home-container">
    <!-- 头部区域 -->
    <el-header class="toubu" style="background-color: #081146">
      <div style="display: flex; align-items: center; width: 100%">
        <!-- 左侧logo -->
        <div style="flex: 1">
          <img src="../assets/image/智慧社区logo3.png" alt="未加载" height="240px" width="250px">
        </div>
        <!-- 顶部中间标题 -->
        <div style="flex: 1; text-align: center">
          <span style="color: black; font-size: 34px">智慧社区后台管理系统</span>
        </div>
        <!-- 右侧菜单 -->
        <div style="flex: 1; text-align: right">
          <el-menu class="el-menu-demo" mode="horizontal"
                   background-color="rgba(0,0,0,0)" text-color="black"
                   active-text-color="#ffd04b" style="float: right">
            <el-submenu index="2" style="position: relative;">
              <template slot="title">
                <div v-if='imageTX==""'>
                  <img src="../assets/image/冠希1.jpg" alt="未"
                       style="width: 55px;height: 59px;border-radius: 50%;display: block;">
                </div>
                <div v-else>
                  <img :src="imageTX" alt="加载失败"
                       style="width: 55px;height: 59px;border-radius: 50%;display: block;color: black;">
                </div>
              </template>
              <div style="position: absolute; top: 100%; left: 0; width: 100%;">
                <el-menu-item style="color: gold;width: 100%;text-align: center;" index="2-1" @click="userInfo">个人中心
                </el-menu-item>
                <el-menu-item style="color: gold;width: 100%;text-align: center;" index="2-3" @click="logout">退出
                </el-menu-item>
              </div>
            </el-submenu>
          </el-menu>
        </div>
        <div style="color: black;">{{ username }}</div>
      </div>
    </el-header>
    <!-- 页面主体区域 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside class="cebianlan" width="220px" style="background-color: #020c46">
        <el-menu
            :default-active="activePath"
            background-color="rgba(255,255,255,0)"
            text-color="lightgoldenrodyellow"
            active-text-color="gold"
            unique-opened
            @select="changerMenu"
        >
          <el-menu-item index="/welcome">
            <i class="el-icon-s-home"></i>
            <span slot="title">首页</span>
          </el-menu-item>
          <el-submenu v-for="item in menuList" :key="item.menuId" :index="item.menuId.toString()">
            <template slot="title">
              <i :class="iconsObj[item.menuId]"></i>
              {{ item.menuName }}
            </template>
            <el-menu-item-group>
              <el-menu-item v-for="subitem in item.children" :index="'/'+subitem.path" :key="subitem.menuId">
                <i :class="iconsObj[subitem.menuId]"></i>{{ subitem.menuName }}
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>
      <!-- 主体结构 -->
      <el-main class="zhuti" style="background-color: rgba(225,195,240,.3)">
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>

import axios from "axios";

export default {
  data() {
    return {
      imageTX: "",
      menuList: [],
      iconsObj: {
        1: 'iconfont icon-system',
        2: 'iconfont icon-monitor',
        3: 'iconfont icon-tool',
        100: 'iconfont icon-user',
        101: 'iconfont icon-peoples',
        102: 'iconfont icon-tree-table',
        103: 'iconfont icon-tree',
        104: 'iconfont icon-post',
        105: 'iconfont icon-dict',
        108: 'iconfont icon-log',
        109: 'iconfont icon-online',
        111: 'iconfont icon-druid',
        112: 'iconfont icon-server',
        113: 'iconfont icon-redis',
        116: 'iconfont icon-swagger',
        2000: 'iconfont icon-property',
        2006: 'iconfont icon-sqzc',
        2008: 'iconfont icon-room',
        2014: 'iconfont icon-building',
        2020: 'iconfont icon-unit',
        2027: 'iconfont icon-bd',
        2033: 'iconfont icon-xqgl',
        2034: 'iconfont icon-yz',
        2045: 'iconfont icon-phone',
        2046: 'iconfont icon-wechat',
        2047: 'iconfont icon-fk',
        2048: 'iconfont icon-fkxx',
        2054: 'iconfont icon-tsjy',
        2060: 'iconfont icon-ts',
        2061: 'iconfont icon-bxxx',
        2067: 'iconfont icon-bx',
      },
      activePath: "",
      username: ""
    }
  },
  mounted() {
    //添加 beforeunload 事件监听：当用户尝试关闭或刷新页面时触发，调用 beforeunloadHandler 方法（通常用于提示用户保存未提交的数据
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
    //添加 unload 事件监听：当页面完全卸载时触发，调用 unloadHandler 方法（可用于清理资源或发送日志）。
    window.addEventListener('unload', e => this.unloadHandler(e))
  },
  destroyed() {
    //移除 beforeunload 和 unload 的事件监听，防止组件销毁后仍被调用。
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.removeEventListener('unload', e => this.unloadHandler(e))
  },
  created() {
    this.getMenuList()
    const cookies = document.cookie.split(';');
    for (const cookie of cookies) {
      const [cookieName, cookieValue] = cookie.split('=');
      if (cookieName === "userName") {
        this.username = decodeURIComponent(cookieValue); // 解码特殊字符（如 %20）
      }
    }
    // document.cookie.split('=')[2]
    // console.log("home->获取cookie:", document.cookie)
    //获取浏览器存储的组件，登录页面时就会停留在上一次关闭时的页面
    this.activePath = window.sessionStorage.getItem('activePath') || ''
    this.imageTX = window.sessionStorage.getItem("avatar")
  },
  methods: {
    userInfo() {
      this.$router.push('/userInfo')
    },
    beforeunloadHandler() {
      this._beforeUnload_time = new Date().getTime();
    },
    //页面完全卸载时，
    unloadHandler(e) {
      // console.log("home-unloadHandler->e=", e)
      this._gap_time = new Date().getTime() - this._beforeUnload_time;
      // eslint-disable-next-line no-debugger
      // debugger
      //判断是窗口关闭还是刷新
      if (this._gap_time <= 5) {
        //如果是登录状态，关闭窗口前，移除用户
        this.$http.get('sys/userOut');
      }
    },
    logout() {
      // 发送请求,由于后端token没保存在redis，直接清除浏览器缓存即可
      // await this.$http.get('sys/userOut');
      this.$message.success("退出成功！")
      window.sessionStorage.clear()
      this.$router.push('/login');
    },
    getMenuList() {
      // 发送请求
      this.$http.get('menu/menus')
          .then((res) => {
            this.menuList = res.data
            // console.log("home->侧边栏menuList=", this.menuList)
          })
          .catch((res) => {
            if (res?.msg !== "") {
              this.$message.error(res.msg)
              // this.$router.push("/login");
              return;
            } else {
              this.$message.error("出错了")
            }

          })
    },
    //点击菜单的时候把菜单组件路径存储在浏览器中
    changerMenu(key, keyPath) {
      this.activePath = String(key);  // 更新高亮状态
      window.sessionStorage.setItem('activePath', key);

      // 只有当前路由不等于目标时才跳转（避免重复导航错误）
      if (this.$route.path !== key) {
        this.$router.push(key)
            .catch(err => {
              this.$message.warning("跳转失败")
            });
      }
    },
  }
}

</script>

<style lang="less" scoped>
.home-container {
  height: 100%;
  width: 100%;
}

.el-header {
  background-color: #373d41;
  display: flex;
  justify-content: space-between;
  padding-left: 0;
  align-items: center;
  color: #fff;
  font-size: 20px;

  > div {
    display: flex;
    align-items: center;

    span {
      margin-left: 15px;
    }
  }
}

.el-aside {
  background-color: #333744;

  .el-menu {
    border-right: none;
  }
}

.el-main {
  background-color: #eaedf1;
}

.iconfont {
  margin-right: 10px;
}

.toggle-button {
  background-color: #4a5064;
  font-size: 10px;
  line-height: 24px;
  color: #fff;
  text-align: center;
  letter-spacing: 0.2em;
  cursor: pointer;
}

.toubu {
  background: url("../assets/image/头部导航2.jpg");
  background-size: 1920px 60px;
}

.cebianlan {
  // background: url("../assets/image/侧边栏4.jpg");
  // background-color: #020c46;
  background-size: 223px 1030px;
}

// .zhuti{
//   background: url("../assets/image/头部导航3.jpg");
//   background-size: 100% 100%;
// }
</style>
